#include "StdAfx.h"
#include "ImageViewer.h"
//////////////////////////////////////////////////////////////////////////
NAMESPACE_BEGIN_UI
//////////////////////////////////////////////////////////////////////////
ImageViewer::ImageViewer(void) : Control()
{
	m_refPalette = nullptr;
	m_refImage = nullptr;
	m_emPictureBoxSizeMode = PictureBoxSizeMode::Normal;

	SetStyle(ControlStyles::UserPaint, true);
	SetStyle(ControlStyles::AllPaintingInWmPaint, true);
	SetStyle(ControlStyles::DoubleBuffer, true);
	SetStyle(ControlStyles::OptimizedDoubleBuffer, true);
	SetStyle(ControlStyles::ResizeRedraw, true);

	InitializeComponent();
}

void ImageViewer::OnPaint(PaintEventArgs^ pe)
{
	pe->Graphics->FillRectangle(gcnew SolidBrush(this->BackColor), this->ClientRectangle);
	if (m_refImage != nullptr && m_refImage->Width != 0 && m_refImage->Height != 0)
	{
		float xratio, yratio, ratio;
		RectangleF sourceRegion = RectangleF::Empty;
		RectangleF targetRegion = RectangleF::Empty;
		RectangleF clientRegion = RectangleToRectangleF(this->ClientRectangle);
		PointF center = PointF(this->ClientRectangle.Width / 2.0f + this->ClientRectangle.X, 
			this->ClientRectangle.Height / 2.0f + this->ClientRectangle.Y);
		switch (this->SizeMode)
		{
		case PictureBoxSizeMode::AutoSize:
		case PictureBoxSizeMode::StretchImage:
			sourceRegion = RectangleF((float)0, (float)0, (float)m_refImage->Width, (float)m_refImage->Height);
			targetRegion = clientRegion;
			break;
		case PictureBoxSizeMode::CenterImage:
			sourceRegion = RectangleF(center.X - m_refImage->Width / 2.0f, 
				center.Y - m_refImage->Height / 2.0f, (float)m_refImage->Width, (float)m_refImage->Height);
			sourceRegion = RectangleF::Intersect(sourceRegion, clientRegion);
			targetRegion = sourceRegion;
			break;
		case PictureBoxSizeMode::Zoom:
			sourceRegion = RectangleF((float)0, (float)0, (float)m_refImage->Width, (float)m_refImage->Height);
			xratio = this->ClientRectangle.Width / sourceRegion.Width;
			yratio = this->ClientRectangle.Height / sourceRegion.Height;
			ratio = System::Math::Min(xratio, yratio);
			targetRegion.Width = sourceRegion.Width * ratio;
			targetRegion.Height = sourceRegion.Height * ratio;
			targetRegion.X = (this->ClientSize.Width - targetRegion.Width) / 2 + this->ClientRectangle.X;
			targetRegion.Y = (this->ClientSize.Height - targetRegion.Height) / 2 + this->ClientRectangle.Y;
			break;
		case PictureBoxSizeMode::Normal:
			sourceRegion = RectangleF((float)0, (float)0, (float)m_refImage->Width, (float)m_refImage->Height);
			sourceRegion = RectangleF::Intersect(sourceRegion, clientRegion);
			targetRegion = sourceRegion;
			break;
		}
		pe->Graphics->DrawImage(m_refImage, targetRegion, sourceRegion, GraphicsUnit::Pixel);
	}
}

//////////////////////////////////////////////////////////////////////////
NAMESPACE_END_UI
//////////////////////////////////////////////////////////////////////////